<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="菜品名称" prop="foodName">
              <el-input v-model="queryParams.foodName" placeholder="请输入美食名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['kitchen:food:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['kitchen:food:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['kitchen:food:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="Download" @click="handleExport" v-hasPermi="['kitchen:food:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="foodList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="美食名称" align="center" prop="foodName" />
<!--        <el-table-column label="菜品分类" align="center" prop="foodTypeId" />-->
        <el-table-column label="菜品分类" align="center" prop="foodTypeName" />
        <el-table-column label="美食图片" align="center" prop="imgUrl" />
        <el-table-column label="菜系" align="center" prop="cuisineType" />
        <el-table-column label="价格" align="center" prop="price">
          <template #default="scope">
            {{ scope.row.price + '元 / ' +scope.row.count + ' / ' + scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="重量" align="center" prop="weight" />
        <el-table-column label="产地" align="center" prop="origin" />
        <el-table-column label="排序索引" align="center" prop="sort" />
        <el-table-column label="备注信息" align="center" prop="remark" />
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="module_state" :value="scope.row.state"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['kitchen:food:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['kitchen:food:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改套餐里的美食信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="foodFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜品分类" prop="foodTypeId">
              <el-select v-model="form.foodTypeId" placeholder="请选择菜品分类" clearable @change="selectType">
                <el-option v-for="item in foodTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="美食名称" prop="foodName">
              <el-input v-model="form.foodName" placeholder="请输入美食名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属菜系" prop="cuisineType">
              <el-select v-model="form.cuisineType" placeholder="请选择菜品分类" clearable>
                <el-option v-for="dict in cuisine_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="count">
              <el-input v-model="form.count" type="number" placeholder="请输入数量" style="width: 50%;"/>
              <el-input v-model="form.unit" placeholder="单位,份;盘" style="width: 50%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入重量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产地" prop="origin">
              <el-input v-model="form.origin" placeholder="请输入产地" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序索引" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序索引" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="form.state">
                <el-radio v-for="dict in module_state" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="美食图片" prop="imgUrl">
              <el-input v-model="form.imgUrl" placeholder="请输入美食图片" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Food" lang="ts">
import { listFood, getFood, delFood, addFood, updateFood } from '@/api/kitchen/food';
import { FoodVO, FoodQuery, FoodForm } from '@/api/kitchen/food/types';
import {listNoPageFoodType} from "@/api/kitchen/food/type";
import {FoodTypeVO} from "@/api/kitchen/food/type/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { module_state, cuisine_type } = toRefs<any>(proxy?.useDict('module_state', 'cuisine_type'));

const foodList = ref<FoodVO[]>([]);
const foodTypeList = ref<FoodTypeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const foodFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: FoodForm = {
  id: undefined,
  foodName: undefined,
  foodTypeId: undefined,
  foodTypeName: undefined,
  imgUrl: undefined,
  count: undefined,
  price: undefined,
  unit: undefined,
  weight: undefined,
  origin: undefined,
  sort: undefined,
  remark: undefined,
  state: undefined
}
const data = reactive<PageData<FoodForm, FoodQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    foodName: undefined,
    foodTypeId: undefined,
    foodTypeName: undefined,
    imgUrl: undefined,
    count: undefined,
    unit: undefined,
    weight: undefined,
    origin: undefined,
    sort: undefined,
    state: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    foodName: [
      { required: true, message: "美食名称不能为空", trigger: "blur" }
    ],
    foodTypeId: [
      { required: true, message: "菜品分类不能为空", trigger: "blur" }
    ],
    foodTypeName: [
      { required: true, message: "菜品分类名称不能为空", trigger: "blur" }
    ],
    count: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "单份的单位不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序索引不能为空", trigger: "blur" }
    ],
    state: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询套餐里的美食信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFood(queryParams.value);
  foodList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询套餐里的美食信息列表 */
const getFoodList = async () => {
  const res = await listNoPageFoodType(queryParams.value);
  foodTypeList.value = res.data;
}

/**
 *  菜品分类change事件
 * @param val
 */
const selectType = (val) => {
  console.log('selectType', val);
  let type = foodTypeList.value.find(option => option.id == val);
  form.value.foodTypeName = type.typeName;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  foodFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: FoodVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getFoodList();
  dialog.visible = true;
  dialog.title = "添加套餐里的美食信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: FoodVO) => {
  reset();
  getFoodList();
  const _id = row?.id || ids.value[0]
  const res = await getFood(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改套餐里的美食信息";
}

/** 提交按钮 */
const submitForm = () => {
  foodFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateFood(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addFood(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: FoodVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除套餐里的美食信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delFood(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('kitchen/food/export', {
    ...queryParams.value
  }, `food_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
